package com.fzj.example.socket.udp;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * ClassName: UDPA
 * date: 2019/11/14 10:25
 * Description: TODO
 *
 * @author fanzj@bonree.com
 * @since JDK 1.8
 */
public class UDPA {
    public static void main(String[] args) {
        AtomicInteger flag=new AtomicInteger(1);
        try {
            Scanner scanner=new Scanner(System.in);
            InetAddress inetAddress=InetAddress.getByName("192.168.0.23");
            DatagramSocket datagramSocket=new DatagramSocket(6788,inetAddress);
            DatagramPacket datagramPacketRec=new DatagramPacket(new byte[2048],2048,inetAddress,6789);
            Runnable runnable1=()->{
                //阻塞
                while (true) try {
                    datagramSocket.receive(datagramPacketRec);
                    String str = new String(datagramPacketRec.getData(), 0, datagramPacketRec.getLength());
                    System.out.println("*****************ly:" + str);
                } catch (IOException e) {
                    flag.set(0);
                    e.printStackTrace();
                }
            };
            Runnable runnable2=()->{
                while (scanner.hasNext()){
                    String msg=scanner.nextLine();
                    try {
                        DatagramPacket datagramPacketSend=new DatagramPacket(msg.getBytes("UTF-8"),msg.getBytes().length,inetAddress,6789);
                        datagramSocket.send(datagramPacketSend);
                    } catch (IOException e) {
                        flag.set(0);
                        e.printStackTrace();
                    }
                }
            };
            Runnable runnable=()->{
                while (flag.get()==0){
                    datagramSocket.close();
                }
            };
            ExecutorService executorService= Executors.newFixedThreadPool(10);
            executorService.submit(runnable);
            executorService.submit(runnable1);
            executorService.submit(runnable2);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
